<template>
  <view class="detail-view">
    <u-form label-width="150" :model="add_form" ref="uForm">
      <view class="form-model-view">
        <u-form-item required label="收款单位" prop="customerName">
          <u-input
            @click="goPage('/pagesT/customer/selCustomer')"
            class="dis-input"
            disabled
            v-model="add_form.customerName"
            placeholder="请选择"
          />
          <u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
        </u-form-item>
        <u-form-item label="收款人">
          <view class="form-value">{{ add_form.operatorName }}</view>
        </u-form-item>
        <u-form-item label="当前应收">
          <view class="form-value">{{
            $utils.formattedNumber(add_form.receivable)
          }}</view>
        </u-form-item>
        <u-form-item label="所属店铺">
          <view
            class="clearfix form-val"
            @click="goPage('/pagesT/shop/selShop')"
          >
            <view class="float_right" @click.stop="add_form.shopId = ''">
              <u-icon
                :name="!add_form.shopId ? 'arrow-right' : 'close-circle-fill'"
                size="28"
                color="#999999"
              >
              </u-icon>
            </view>
            <text class="float_right ellipsis">{{
              add_form.shopId ? add_form.shopName : "请选择"
            }}</text>
          </view>
        </u-form-item>
      </view>
      <view class="form-model-view">
        <u-form-item label="收款单明细">
          <view class="form-value add-btn-go" @click="addAccount">
            <u-icon name="plus" size="24" color="#fb5904"></u-icon>
            <text class="form-value add-text">添加收款</text>
          </view>
        </u-form-item>
        <view class="detail-ul">
          <view
            class="detail-li"
            v-for="(item, index) in add_form.receiptRequisitionAccountDate"
            :key="index"
          >
            <view class="del-icon" @click="delAccount(index)">
              <u-icon
                name="minus-circle-fill"
                size="40"
                color="#fb5904"
              ></u-icon>
            </view>
            <view class="title clearfix">
              <view class="float_left">结算方式</view>
              <view class="float_right" @click="openMethods(index)">
                <text>{{
                  item.settlementMethod !== ""
                    ? pay_type_list[item.settlementMethod - 1].label
                    : "请选择"
                }}</text>
                <u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
              </view>
            </view>
            <u-form-item label="结算账户">
              <view class="clearfix form-val" @click="settlementAccount(index)">
                <view class="float_right" @click.stop="delsettlementAccount">
                  <u-icon
                    :name="
                      !item.accountId ? 'arrow-right' : 'close-circle-fill'
                    "
                    size="28"
                    color="#999999"
                  >
                  </u-icon>
                </view>
                <text class="float_right ellipsis">{{
                  item.accountId ? item.accountName : "请选择"
                }}</text>
              </view>
            </u-form-item>
            <view class="money-ul">
              <view class="money-li"
                ><input
                  type="digit"
                  @blur="moneyChange(index)"
                  v-model="item.collectionAmount"
                  placeholder="收款金额"
              /></view>
              <view class="money-li"
                ><input
                  type="digit"
                  @blur="moneyChange(index)"
                  v-model="item.preferentialAmount"
                  placeholder="优惠金额"
              /></view>
              <view class="money-li"
                ><input
                  type="digit"
                  v-model="item.actualAmount"
                  placeholder="实收金额"
                />
              </view>
            </view>
            <view class="bottom clearfix"
              ><input type="text" v-model="item.remark" placeholder="备注" />
            </view>
          </view>
        </view>
      </view>
      <view class="form-model-view">
        <u-form-item label="收款总额">
          <view class="form-value">{{ totalCollectionAmount }}</view>
        </u-form-item>
        <u-form-item label="优惠总额">
          <view class="form-value">{{ totalPreferentialAmount }}</view>
        </u-form-item>
        <u-form-item label="实收总额">
          <view class="form-value">{{ totalActualAmount }}</view>
        </u-form-item>
      </view>
    </u-form>
    <u-select
      @confirm="methodsConfirm"
      v-model="methods_show"
      :list="pay_type_list"
    ></u-select>
    <view class="detail-bottom">
      <view class="handel-btn" @click="submit">提交订单</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      rules: {
        customerName: [
          {
            required: true,
            message: "请选择收款单位",
            trigger: ["change", "blur"],
          },
        ],
      },
      add_form: {
        customerId: "",
        customerName: "",
        operatorId: "",
        operatorName: "",
        receivable: "",
        shopId: "",
        shopName: "",
        receiptRequisitionAccountDate: [
          {
            collectionAmount: "",
            preferentialAmount: "",
            actualAmount: "",
            settlementMethod: "",
            remark: "",
            accountName: "",
            accountId: "",
          },
        ],
      },
      methods_show: false,
      account_index: 0,
      pay_type_list: [
        {
          value: 1,
          label: "当面现金",
        },
        {
          value: 2,
          label: "私人微信",
        },
        {
          value: 3,
          label: "私人支付宝",
        },
        {
          value: 4,
          label: "私人银行卡",
        },
        {
          value: 5,
          label: "公司公户",
        },
        {
          value: 6,
          label: "公司微信",
        },
        {
          value: 7,
          label: "公司支付宝",
        },
        {
          value: 8,
          label: "公司银行卡",
        },
      ],
      customerData: "",
      account_id: "",
      shopData: {},
      AccountData: {},
      index: "",
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
    // 收款总额
    totalCollectionAmount() {
      if (!this.add_form.receiptRequisitionAccountDate.length) {
        return 0;
      } else if (this.add_form.receiptRequisitionAccountDate.length === 1) {
        return Number(
          this.add_form.receiptRequisitionAccountDate[0].collectionAmount
        );
      } else {
        let sum = 0;
        this.add_form.receiptRequisitionAccountDate.forEach((item) => {
          sum = this.$NP.plus(sum, Number(item.collectionAmount) || 0);
        });
        return sum;
      }
    },
    // 优惠总额
    totalPreferentialAmount() {
      if (!this.add_form.receiptRequisitionAccountDate.length) {
        return 0;
      } else if (this.add_form.receiptRequisitionAccountDate.length === 1) {
        return Number(
          this.add_form.receiptRequisitionAccountDate[0].preferentialAmount
        );
      } else {
        let sum = 0;
        this.add_form.receiptRequisitionAccountDate.forEach((item) => {
          sum = this.$NP.plus(sum, Number(item.preferentialAmount) || 0);
        });
        return sum;
      }
    },
    // 实收总额
    totalActualAmount() {
      if (!this.add_form.receiptRequisitionAccountDate.length) {
        return 0;
      } else if (this.add_form.receiptRequisitionAccountDate.length === 1) {
        return Number(
          this.add_form.receiptRequisitionAccountDate[0].actualAmount
        );
      } else {
        let sum = 0;
        this.add_form.receiptRequisitionAccountDate.forEach((item) => {
          sum = this.$NP.plus(sum, Number(item.actualAmount) || 0);
        });
        return sum;
      }
    },
  },
  watch: {
    customerData(val) {
      if (val) {
        this.add_form.customerId = val.id;
        this.add_form.customerName = val.name;
        this.add_form.receivable = val.money;
      }
    },
    // 店铺
    shopData(val) {
      if (val) {
        this.add_form.shopName = val.name;
        this.add_form.shopId = val.id;
      }
    },
    AccountData(val) {
      if (val) {
        console.log(val);
        this.add_form.receiptRequisitionAccountDate[this.index].accountId =
          val.id;
        this.add_form.receiptRequisitionAccountDate[this.index].accountName =
          val.name;
      }
    },
  },
  onLoad(options) {
    if (options.id) {
      this.account_id = options.id;
      uni.setNavigationBarTitle({
        title: "编辑收款申请单",
      });
      this.getReceiptRequisitionInfo();
    } else {
      this.add_form.operatorId = this.userInfo.userCenterId;
      this.add_form.operatorName = this.userInfo.name || "";
    }
  },
  methods: {
    // 详情
    getReceiptRequisitionInfo() {
      this.$u.api
        .getReceiptRequisitionInfo(this.account_id)
        .then(({ data }) => {
          this.add_form = {
            customerId: data.customerId,
            customerName: data.customerName,
            operatorId: data.operatorId,
            operatorName: data.operatorName,
            receivable: data.receivable,
            receiptRequisitionAccountDate: data.accountList.map((item) => {
              return {
                ...item,
                settlementMethod: item.settlementMethod,
              };
            }),
          };
        });
    },
    openMethods(index) {
      this.methods_show = true;
      this.account_index = index;
    },
    methodsConfirm(arr) {
      this.add_form.receiptRequisitionAccountDate[
        this.account_index
      ].settlementMethod = arr[0].value;
    },
    addAccount() {
      this.add_form.receiptRequisitionAccountDate.push({
        collectionAmount: "",
        preferentialAmount: "",
        actualAmount: "",
        settlementMethod: "",
        remark: "",
      });
    },
    delAccount(index) {
      if (this.add_form.receiptRequisitionAccountDate.length === 1) {
        this.$u.toast("至少保留一条");
        return;
      }
      this.add_form.receiptRequisitionAccountDate.splice(index, 1);
    },
    moneyChange(index) {
      const target = this.$u.deepClone(
        this.add_form.receiptRequisitionAccountDate
      );
      //优惠金额不能大于收款金额
      if (
        Number(target[index].preferentialAmount) >
        Number(target[index].collectionAmount)
      ) {
        target[index].preferentialAmount = Number(
          target[index].collectionAmount
        );
      }
      let collectionAmount = target[index].collectionAmount;
      let preferentialAmount = target[index].preferentialAmount;
      target[index].actualAmount = this.$NP.minus(
        collectionAmount,
        preferentialAmount
      );
      this.add_form.receiptRequisitionAccountDate = target;
    },
    //  添加
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.add_form,
            totalCollectionAmount: this.totalCollectionAmount,
            totalPreferentialAmount: this.totalPreferentialAmount,
            totalActualAmount: this.totalActualAmount,
          };
          let isSub = true;
          for (let i in this.add_form.receiptRequisitionAccountDate) {
            let item = this.add_form.receiptRequisitionAccountDate[i];
            if (!item.collectionAmount) {
              isSub = false;
              this.$u.toast("请输入收款金额");
              break;
            }
            if (!item.settlementMethod) {
              isSub = false;
              this.$u.toast("请选择结算方式");
              break;
            }
            if (!item.accountId) {
              isSub = false;
              this.$u.toast("请选择结算账户");
              break;
            }
          }
          if (!isSub) {
            return;
          }
          if (this.account_id) {
            this.$u.api
              .editReceiptRequisition(this.account_id, params)
              .then((res) => {
                this.$u.toast("修改成功");
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              });
          } else {
            this.$u.api.addReceiptRequisition(params).then((res) => {
              this.$u.toast("新增成功");
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            });
          }
        }
      });
    },
    settlementAccount(index) {
      if (!this.add_form.shopId) {
        this.$u.toast("必须先选择商铺");
        return;
      }
      this.goPage("/pagesT/account/selAccount");
      this.index = index;
    },
    delsettlementAccount() {
      this.add_form.receiptRequisitionAccountDate[this.index].accountId = "";
      this.add_form.receiptRequisitionAccountDate[this.index].accountName = "";
    },
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>

<style lang="scss" scoped>
.detail-ul {
  .detail-li {
    padding-left: 60rpx;
    position: relative;
    border-bottom: 1px solid #eeeeee;

    &:last-child {
      border-bottom: 0 none;
    }

    .del-icon {
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
    }

    .title {
      line-height: 80rpx;
    }

    .money-ul {
      border-top: 1px solid #eeeeee;
      padding: 20rpx 0;
      display: flex;

      .money-li {
        flex: 3;
        border-right: 1px solid #eeeeee;

        input {
          height: 80rpx;
          line-height: 80rpx;
          text-align: center;
        }

        &:last-child {
          border-right: 0 none;
        }
      }
    }

    .bottom {
      border-top: 1px solid #eeeeee;

      input {
        height: 80rpx;
        line-height: 80rpx;
      }
    }
  }
}
.form-value {
  .add-text {
    color: #fb5904;
  }
}
.handel-btn {
  background-color: #fb5904 !important;
  border-color: #fb5904 !important;
}
</style>
